package com.hn.kiss.modules.sys.shopcommon.util;

import com.github.pagehelper.util.StringUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.LoggerFactory;

/**
 * 汉字转拼音工具
 * @author space
 *
 */
public class PinyinUtil {
	/**
	 * 汉字转换位汉语拼音首字母，英文字符不变
	 * 
	 * @param chines
	 *            汉字
	 * @return 拼音
	 */
	public static String converterToFirstSpell(String chines) {
		if(StringUtil.isEmpty(chines)){
			return null;
		}
		String pinyinName = "";
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		String[]pyArray = null;
		for (int i = 0; i < nameChar.length; i++) {
			if (nameChar[i] > 128) {
				try {
					pyArray = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
					if(pyArray!=null&&pyArray.length>0){
						pinyinName += pyArray[0].charAt(0);
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					LoggerFactory.getLogger(PinyinUtil.class).error("汉语转拼音失败！目标汉语为："+chines+"。错误信息："+e.getMessage());
					e.printStackTrace();
				}
			} else {
				pinyinName += nameChar[i];
			}
		}
		return pinyinName;
	}

	/**
	 * 汉字转换位汉语拼音，英文字符不变
	 * 
	 * @param chines
	 *            汉字
	 * @return 拼音
	 */
	public static String converterToSpell(String chines) {
		if(StringUtil.isEmpty(chines)){
			return null;
		}
		String pinyinName = "";
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		String[]pyArray = null;
		for (int i = 0; i < nameChar.length; i++) {
			if (nameChar[i] > 128) {
				try {
					pyArray = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
					if(pyArray!=null&&pyArray.length>0){
						pinyinName += pyArray[0];
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					LoggerFactory.getLogger(PinyinUtil.class).error("汉语转拼音首字母失败！目标汉语为："+chines+"。错误信息："+e.getMessage());
					e.printStackTrace();
				}
			} else {
				pinyinName += nameChar[i];
			}
		}
		return pinyinName;
	}
}
